using UnityEngine;
using UnityEngine.UI;
using System;

[AddComponentMenu("TagMachine/UI/Menu/Preference Saver")]
public class UIPreferenceSaver : MonoBehaviour
{
	public string PreferenceName 	= "";

	public bool UseObjectName 		= true;
	public string NameDelimiter 	= "_";

	// Linked element
	private Toggle m_ToggleElem 	= null;
	private Slider m_SliderElem 	= null;

	void Awake()
	{
		if ( UseObjectName )
		{
			PreferenceName = name.Substring( name.IndexOf( NameDelimiter ) + 1 );
		}
	}

	void Start()
	{
		// Toggle
		m_ToggleElem = GetComponentInChildren< Toggle >();
		if ( m_ToggleElem != null )
		{
			m_ToggleElem.onValueChanged.AddListener( SavePreference );
			SavePreference( m_ToggleElem.isOn );
		}

		// Slider
		m_SliderElem = GetComponentInChildren< Slider >();
		if ( m_SliderElem != null )
		{
			m_SliderElem.onValueChanged.AddListener( SavePreference );
			SavePreference( m_SliderElem.value );
		}
	}

	public void SavePreference( string _Value )
	{
		PlayerPrefs.SetString( PreferenceName, _Value );
	}

	public void SavePreference( int _Value )
	{
		PlayerPrefs.SetInt( PreferenceName, _Value );
	}

	public void SavePreference( float _Value )
	{
		if ( m_SliderElem != null && m_SliderElem.wholeNumbers )
		{
			PlayerPrefs.SetInt( PreferenceName, (int)_Value );
		}
		else
		{
			PlayerPrefs.SetFloat( PreferenceName, _Value );
		}
	}

	public void SavePreference( bool _Value )
	{
		PlayerPrefs.SetInt( PreferenceName, _Value ? 1 : 0 );
	}
}